package org.report4service.views;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;

import org.report4service.listeners.AlertMessageListener;
import org.report4service.listeners.LogonListner;
import org.report4service.services.ReportServiceImpl;
import org.report4service.services.UserServiceImpl;
import org.report4service.utils.AlertMessage;
import org.report4service.utils.CommandPool;
import org.report4service.utils.TextPool;

/**
 * Changes user's password
 * 
 * @author Jmpango
 * 
 */
public class ChangePassword extends Form implements CommandListener, AlertMessageListener {

    /** Reference to which form to display */
    private Display display;

    /** Reference to the previous Screen/Form */
    private Displayable prvScreen;

    /** Application title */
    private String title;

    /** LogonListner */
    private LogonListner logonListner;

    /** Display alerts */
    private AlertMessage alertMessage;

    /** Input for current user password */
    private TextField currentPassword;

    /** Input for user new password */
    private TextField newPassword;

    /** Input to confirm user new password */
    private TextField confirmNewPassword;

    /** Check if changes are saved sucessfully */
    private boolean isSuccessfullySaved = false;

    private UserServiceImpl userService;
    private ReportServiceImpl reportService;

    public ChangePassword(Display display, Displayable prvScreen, String title,
	    LogonListner logonListner, UserServiceImpl userService, ReportServiceImpl reportService) {
	super(title);
	setDisplay(display);
	setPrvScreen(prvScreen);
	setLogonListner(logonListner);
	setUserService(userService);
        setReportService(reportService);
	createChangePasswordForm();
    }

    /**
     * creates the form
     */
    private void createChangePasswordForm() {
	currentPassword = new TextField(TextPool.CURRENT_PASSWORD(), null, 4, TextField.NUMERIC|TextField.PASSWORD);
	newPassword = new TextField(TextPool.NEW_PASSWORD(), null, 4, TextField.NUMERIC|TextField.PASSWORD);
	confirmNewPassword = new TextField(TextPool.CONFIRM_PASSWORD(), null, 4, TextField.NUMERIC|TextField.PASSWORD);

        append("Change Password\n");
	append(currentPassword);
	append(newPassword);
	append(confirmNewPassword);

	this.addCommand(CommandPool.btnOk);
	this.addCommand(CommandPool.btnBack);
	this.setCommandListener(this);

	getDisplay().setCurrent(this);

    }

    public void commandAction(Command command, Displayable arg1) {
	if (command.equals(CommandPool.btnOk)) {
	    if (currentPassword.getString().trim().equals(TextPool.EMPTY_STRING())) {
		displayAlert("Current Password can't be empty");
	    } else if (newPassword.getString().trim().equals(TextPool.EMPTY_STRING())) {
		displayAlert("New password can't be empty ");
	    } else if (!(newPassword.getString().trim()
		    .equals(confirmNewPassword.getString().trim()))) {
		displayAlert("New password and confirmed password don't match");
	    } else if (!(userService.getUser().getPassword().equals(currentPassword
		    .getString().trim()))) {
		displayAlert("The current password is wrong");
	    } else if (newPassword.getString()
			.trim().length() < 4) {
		displayAlert("Password should be four(4) digits");
	    } else {
		saveUserCredentialChange(newPassword.getString().trim());
	    }
	}

	if (command.equals(CommandPool.btnBack)) {
            try {
                getUserService().shutDB();
                getReportService().startDB();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
	    getDisplay().setCurrent(getPrvScreen());
	}
    }

    /**
     * @param userChangedPassword
     */
    private void saveUserCredentialChange(String pswd) {
        getUserService().startDB();
	if (getUserService().changeUserPassword(pswd)) {
	    isSuccessfullySaved = true;
	    displayAlert("UserCredentials saved sucessfully");
	} else
	    displayAlert("Password couldn't be changed. Try again.");
    }

    /**
     * Displays an alert with message
     * 
     * @param msg
     * 
     */
    private void displayAlert(String msg) {
	alertMessage = new AlertMessage(getDisplay(), TextPool.TITLE(), this, this);
	alertMessage.show(msg);
    }

    public void onAlertMessage(byte msg) {
	if (msg == AlertMessageListener.MSG_OK) {
	    if (isSuccessfullySaved) {
		isSuccessfullySaved = false;
                cleanUp();
		getDisplay().setCurrent(getPrvScreen());
	    } else
		getDisplay().setCurrent(this);
	}
    }

    private void cleanUp(){
        title = null;
        logonListner = null;
        alertMessage = null;
    }
    /**
     * @return the display
     */
    public Display getDisplay() {
	return display;
    }

    /**
     * @param display
     *            the display to set
     */
    public void setDisplay(Display display) {
	this.display = display;
    }

    /**
     * @return the prvScreen
     */
    public Displayable getPrvScreen() {
	return prvScreen;
    }

    /**
     * @param prvScreen
     *            the prvScreen to set
     */
    public void setPrvScreen(Displayable prvScreen) {
	this.prvScreen = prvScreen;
    }

    /**
     * @return the title
     */
    public String getTitle() {
	return title;
    }

    /**
     * @param title
     *            the title to set
     */
    public void setTitle(String title) {
	this.title = title;
    }

    /**
     * @return the logonListner
     */
    public LogonListner getLogonListner() {
	return logonListner;
    }

    /**
     * @param logonListner
     *            the logonListner to set
     */
    public void setLogonListner(LogonListner logonListner) {
	this.logonListner = logonListner;
    }

    /**
     * @return the alertMessage
     */
    public AlertMessage getAlertMessage() {
	return alertMessage;
    }

    /**
     * @param alertMessage
     *            the alertMessage to set
     */
    public void setAlertMessage(AlertMessage alertMessage) {
	this.alertMessage = alertMessage;
    }

    /**
     * @return the currentPassword
     */
    public TextField getCurrentPassword() {
	return currentPassword;
    }

    /**
     * @param currentPassword
     *            the currentPassword to set
     */
    public void setCurrentPassword(TextField currentPassword) {
	this.currentPassword = currentPassword;
    }

    /**
     * @return the newPassword
     */
    public TextField getNewPassword() {
	return newPassword;
    }

    /**
     * @param newPassword
     *            the newPassword to set
     */
    public void setNewPassword(TextField newPassword) {
	this.newPassword = newPassword;
    }

    /**
     * @return the confirmNewPassword
     */
    public TextField getConfirmNewPassword() {
	return confirmNewPassword;
    }

    /**
     * @param confirmNewPassword
     *            the confirmNewPassword to set
     */
    public void setConfirmNewPassword(TextField confirmNewPassword) {
	this.confirmNewPassword = confirmNewPassword;
    }

    /**
     * @return the isSuccessfullySaved
     */
    public boolean isSuccessfullySaved() {
	return isSuccessfullySaved;
    }

    /**
     * @param isSuccessfullySaved
     *            the isSuccessfullySaved to set
     */
    public void setSuccessfullySaved(boolean isSuccessfullySaved) {
	this.isSuccessfullySaved = isSuccessfullySaved;
    }

    /**
     * @return the userService
     */
    public UserServiceImpl getUserService() {
	return userService;
    }

    /**
     * @param userService
     *            the userService to set
     */
    public void setUserService(UserServiceImpl userService) {
	this.userService = userService;
    }

    public ReportServiceImpl getReportService() {
        return reportService;
    }

    public void setReportService(ReportServiceImpl reportService) {
        this.reportService = reportService;
    }

}
